<?php
namespace api\modules\v1\controllers;

use api\common\controllers\AController;
use common\records\Record;
use common\records\ToyMachine;
use common\records\UserInfo;
use common\records\Order;
use yii\data\ActiveDataProvider;

class UnfinishOrderController extends AController
{
    public $modelClass = 'common\records\Order';
    /**
     * @api {get} /v1/orders 订单列表
     * @apiVersion 1.0.0
     * @apiName index
     * @apiGroup orders 
     *
     *
     */
    public function actionIndex()
    {
        if(!array_key_exists("uid",$_GET) )
        {
            $result = array();
            $detail = array();

            $detail['code'] = 400;
            $detail['reason'] = "fields missing";
            $result['result'] = $detail;
            return $result;
        }
        $uid = trim($_GET['uid']);
        $orders = Order::find()->where(['uid'=>$uid, 'status'=>0])->orderBy('order_id DESC')->all();
        if(count($orders) > 0)
        {
            $user= UserInfo::find()->where(['uid'=>$uid])->one();
            $sum_coin = 0;
            $order_arr = array();
            for($i=0;$i<count($orders);$i++)
            {
                if(time() - strtotime($orders[$i]->timestamp) > 15)
                {
                    $order = array();

                    $order['id'] = $orders[$i]->id;
                    $order['timestamp'] = strtotime($orders[$i]->timestamp);
                    $order['coin'] = $orders[$i]->coin;

                    $order_arr[] = $order;
                    $sum_coin = $sum_coin + $orders[$i]->coin;
                    $orders[$i]->status = 2 //已退款
                }
            }
            if(count($order_arr) > 0)
            {
                $user->coin = $user->coin + $sum_coin;
                $user->save(false);

                $record = new Record();
                $record->uid = $uid;
                $record->coin = $sum_coin;
                $record->type = 3;
                $desp  = "退还未完成订单娃娃币".$sum_coin."个";
                $record->description = $desp;
                $record->timestamp = date('Y-m-d H:i:s',time());
                $record->status = 1;
                $record->save();
                $result = array();
                $detail = array();
                $detail['code'] = 200;
                $detail['reason'] = "success";
                $detail['orders'] = $order_arr;
                $detail['coin'] = $sum_coin;

                $result['result'] = $detail;
                return $result;
            }
        }
        $result = array();
        $detail = array();
        $detail['code'] = 201;
        $detail['reason'] = "no unfinish order";

        $result['result'] = $detail;

        return $result;
    }
    
}
